<?php
//支付回调处理
namespace app\admin\controller;

use app\service\appletService;
use app\service\billService;
use app\service\homeService;
use app\service\lifeapiService;
use printing\printDemo;
use think\Controller;
use think\facade\Db;
use think\facade\Log;
use think\Queue;

class Callback extends Controller{
	
    public function getuser(){
        $api = new lifeapiService();
        //获取当前用户支付宝ID
        $code = request()->get('auth_code');
        $oauthtoken = $api->oauthToken($code);
        
        if(property_exists($oauthtoken,'sub_msg')){
            return json(['info' => $oauthtoken->sub_msg]);
        }
        
        //Log::write($oauthtoken,"oauthtoken");
        session('user_id',$oauthtoken->user_id);
        $url=session("url");
        $this->redirect($url);
        die;    
    }
    //支付宝同步账单回调
    public function notice(){
        /*$path=dir(getcwd())->path.'/pay/online/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100,999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        parse_str(file_get_contents($address),$result);//读取文本并变成数组*/
        if(request()->isPost()){
            
              
            $params = array (
                'notify_time' => $_POST['notify_time'],//通知首次发送时间
                'sign_type' => $_POST['sign_type'],//签名类型
                // 'sign' => $_POST['sign'],//签名类型
                'trade_no' => $_POST['trade_no'],//支付宝交易号
                'buyer_user_id' => $_POST['buyer_user_id'],//买家支付宝账号对应的支付宝唯一用户号
                'buyer_logon_id' => $_POST['buyer_logon_id'],//脱敏后的买家支付宝账号
                'seller_id' => $_POST['seller_id'],//卖家支付宝用户号
                'trade_status' => $_POST['trade_status'],//交易目前所处的状态
                'total_amount' => $_POST['total_amount'],//本次交易支付的订单金额
                'receipt_amount' => $_POST['receipt_amount'],//商家在交易中实际收到的款项
                'refund_fee' => $_POST['refund_fee'],//退款通知中，返回总退款金额
                'body' => $_POST['body'],//交易订单描述
                'det_list' => $_POST['det_list'],//用于标识该笔缴费对应的缴费明细项外部编号
                'gmt_create' => $_POST['gmt_create'],//交易创建时间
                'gmt_payment' => $_POST['gmt_payment'],//交易付款时间
                'fund_bill_list' => $_POST['fund_bill_list'],//交易付款时间
            );
            $postdata=$params;
            $res=Db::table("billpayonline")->where("trade_no",$postdata["trade_no"])->find();


            if(empty($res)){
                $payid=Db::table("billpayonline")->insertGetId($postdata);
                $arr = explode('|',$params['det_list']);
                //查询房屋号
                $out_room_id="";
                $community_id="";
                if(is_array($arr)){
                    $billinfo=Db::name('bill')->where('bill_entry_id', $arr[0])->find();
                    $out_room_id=$billinfo["out_room_id"];
                    $community_id=$billinfo["community_id"];
                }else{
                    $billinfo=Db::name('bill')->where('bill_entry_id', $arr)->find();
                    $out_room_id=$billinfo["out_room_id"];
                    $community_id=$billinfo["community_id"];
                }

                $communtyinfo=Db::table("community")->where("community_id",$community_id)->find();
                if($communtyinfo["auto_invoice_send_status"]=="1"){
                    $jobHandlerClassName  = 'app\admin\job\BillOnlineInvoice';
                    $jobQueueName  	  = "BillOnlineInvoiceQueue";

                    $jobData       	  = [ 'id' => $payid ] ;
                    $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                }
                if($out_room_id=="20210112181751Z4F5RJSU"||$out_room_id=="20210109173434C5Y9TAJ3"){
                    $jobHandlerClassName  = 'app\admin\job\BillOnlineInvoice';
                    $jobQueueName  	  = "BillOnlineInvoiceQueue";

                    $jobData       	  = [ 'id' => $payid ] ;
                    $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                }
            }
                // $sign = (new apiService(null,null))->notice($params);
            if($params['trade_status'] == 'TRADE_SUCCESS'){
                if(!empty($params['det_list'])){
                    $arr = explode('|',$params['det_list']);
                    //根据账单批次号查找数据
                    $list = (new billService())->billApiId($arr);
                    if (count($list) != count($arr)) {
                        echo '没有相应账单';
                        Log::write($arr,"没有相应账单");
                        exit;
                    }
                    $printinglist=array();
                    foreach($list as $lis){
                        $info['pay_type'] = '线上支付宝';//付款类型
                        $info['trade_no'] = $params['trade_no'];//支付宝交易号
                        $info['gmt_payment'] = $params['gmt_payment'];//付款时间
                        $info['status'] = $params['trade_status'];//付款状态
                        $info['id'] = $lis['id'];
                        //修改数据
                        $billedit = (new billService())->billApiEdit($info);
                        $bill['id'][] = $lis['id'];
                        $bill['community_id'] = $lis['community_id'];
                        $bill['room_address'] = $lis['room_address'];
                        $bill['out_room_id'] = $lis['out_room_id'];
                        $bill['detailed'][] = '费用类型: '.$lis['cost_type'];
                        $bill['detailed'][] = '账期: '.$lis['acct_period'];
                        $bill['detailed'][] = '金额: '.$lis['bill_entry_amount'];
                        $bill['trade_no'] = $info['trade_no'];
                        $bill['pay_type'] = $info['pay_type'];
                        $bill['bill_entry_amount'][] = $lis['bill_entry_amount'];
                        $bill['gmt_payment'] = $info['gmt_payment'];
                        $bill['printing'] = $lis['printing'];
                        $printinglist[] = $bill;
                    }
                    $printinglist = $printinglist[count($printinglist)-1];


                    //判断是否已自动打印
                    if($res['printing'] == "0"){
                        //根据小区编号查询打印机终端
                        $community = (new billService())->communityMachine($printinglist['community_id']);
                        
                        $machineCode = $community['machine_code'];//终端号
                        $community_name = $community['community_name'];//小区名称
                        $room_address = $printinglist['room_address'];//门牌号
                        if(!empty($machineCode)){
                            $owner_name = (new billService())->billOwnerName($printinglist['out_room_id']);//业主姓名
                            $detailed = $printinglist['detailed'];//费用类型
                            $trade_no = $printinglist['trade_no'];//支付宝订单号
                            $pay_type = $printinglist['pay_type'];//付款类型
                            $bill_entry_amount = array_sum($printinglist['bill_entry_amount']).'元';//支付金额
                            $gmt_payment = $bill['gmt_payment'];//付款时间
                            $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                            $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_entry_amount,$gmt_payment,$property);
                            if($printing){
                                Db::table("billpayonline")->where("id",$res["id"])->update(['printing' => '1']);
                                foreach($printinglist['id'] as $id){
                                    $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                                }
                            }
                        }
                        
                        echo 'success';
                    }


                }
            }       
        }
    }
    
    //收银台回调
    public function cashierNotice(){
        $path=dir(getcwd())->path.'/pay/cashier/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
             $cashierinfo=Db::table("cashier")->where('trade_no',$result['trade_no'])->find();
             if(!empty($cashierinfo)){
                 if($cashierinfo["status"]=="2"){
                     $res=Db::table("cashier")->where("id",$cashierinfo["id"])->update(["status"=>"1","paytype"=>"支付宝","pay_time"=>$result['gmt_payment']]);
                 }
             }
        }
    }
    
    
    //停车收款回调
    public function gatepayNotice(){
        $path=dir(getcwd())->path.'/pay/gatepay/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
             $billinfo=Db::table("billpark")->where('trade_no',$result['trade_no'])->find();
            if(!empty($billinfo)){
                if($billinfo["order_status"]=="0"){
                     $res=Db::table("billpark")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"1","pay_time"=>$result['gmt_payment']]);
                    if($res){
                        $info=Db::table("billpark")->where("id",$billinfo["id"])->find();
                        $info["pay_time"]=strtotime($info["pay_time"]);
                        $info["buyer_logon_id"]=$result['buyer_logon_id'];
                        
                        Db::table("billparkorder")->insert($info);
                        
                        $gateinfo=Db::table("property_parking_gate")->where("id",$info["gateid"])->find();
                        if(!empty($gateinfo["voice_id"])){
    						$voice_id=$gateinfo["voice_id"];
    						$price=$info['pay_money']*100;
    						$url="http://cloudspeaker.smartlinkall.com/add.php?id=".$voice_id."&uid=API_ZZKJ&token=110921791234&price=".$price."&pt=1";
    						$res=file_get_contents($url);
    						//Log::write($url,"喇叭");
    					}
    					
    					if(!empty($gateinfo["machine_code"])){
    					    $pay_type="支付宝";
    					    $printing = (new printDemo())->gatepayprinting($gateinfo["machine_code"],$info["community_name"],$gateinfo["gateName"],$pay_type,$info["pay_money"],$result['gmt_payment'],$info["remark"]);
    					    if($printing){
    					        Db::table("billparkorder")->where("id",$billinfo["id"])->update(["printing"=>"1"]);
    					    }
    					}
                    }
                     
                }
                
             }
        }
    }
    public function wxgatepayNotice(){
        $path=dir(getcwd())->path.'/pay/gatepaywx/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $billinfo=Db::table("billpark")->where('trade_no',$result['out_trade_no'])->find();
             if(!empty($billinfo)){
                 if($billinfo["order_status"]=="0"){
                     $res=Db::table("billpark")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"2","pay_time"=>$result['time_end']]);
                    if($res){
                        $info=Db::table("billpark")->where("id",$billinfo["id"])->find();
                        $info["pay_time"]=strtotime($info["pay_time"]);
                        Db::table("billparkorder")->insert($info);
                        
                        $gateinfo=Db::table("property_parking_gate")->where("id",$info["gateid"])->find();
                        if(!empty($gateinfo["voice_id"])){
    						$voice_id=$gateinfo["voice_id"];
    						$price=$info['pay_money']*100;
    						$url="http://cloudspeaker.smartlinkall.com/add.php?id=".$voice_id."&uid=API_ZZKJ&token=110921791234&price=".$price."&pt=2";
    						$res=file_get_contents($url);
    						//Log::write($url,"喇叭");
    					}
    					
    					if(!empty($gateinfo["machine_code"])){
    					    $pay_type="支付宝";
    					    $printing = (new printDemo())->gatepayprinting($gateinfo["machine_code"],$info["community_name"],$gateinfo["gateName"],$pay_type,$info["pay_money"],$result['time_end'],$info["remark"]);
    					    if($printing){
    					        Db::table("billparkorder")->where("id",$billinfo["id"])->update(["printing"=>"1"]);
    					    }
    					}
                    }
                     
                 }
             }
                
            
        }
    }
    
   public function test(){
       $jobHandlerClassName  = 'app\admin\job\BillpaySettle';
       $jobQueueName  	  = "BillpaySettleQueue";
       $jobData       	  = [ 'id' => 121245 ] ;
       $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
   }
	//回调信息
    public function alinotice(){

        $path=dir(getcwd())->path.'/pay/aliapplet/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\20190917163824965420.txt';
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            //如果成功返回了
            $payinfo=Db::table("billpay")->where('trade_no',$result['trade_no'])->find();
            if(!empty($payinfo)){
                if($payinfo["order_status"]=="0"){
                    $paydata["id"]=$payinfo["id"];
                    $paydata["order_status"]="1";
                    $paydata['pay_time'] =$result['gmt_payment'];
                    Db::table("billpay")->update($paydata);

                    $communtyinfo=Db::table("community")->where("community_id",$payinfo["community_id"])->find();
                    if($communtyinfo["auto_invoice_send_status"]=="1"){
                        $jobHandlerClassName  = 'app\admin\job\BillInvoice';
                        $jobQueueName  	  = "BillInvoiceQueue";
                        $jobData       	  = [ 'id' => $payinfo["id"] ] ;
                        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                    }
                    /*if($payinfo["out_room_id"]=="20210112181751Z4F5RJSU"||$payinfo["out_room_id"]=="20210109173434C5Y9TAJ3"){
                        $jobHandlerClassName  = 'app\admin\job\BillInvoice';
                        $jobQueueName  	  = "BillInvoiceQueue";
                        $jobData       	  = [ 'id' => $payinfo["id"] ] ;
                        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                    }*/
                    if($payinfo["scenes"]==5){
                        $jobHandlerClassName  = 'app\admin\job\BillpaySettle';
                        $jobQueueName  	  = "BillpaySettleQueue";
                        $jobData       	  = [ 'id' => $payinfo["id"] ] ;
                        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                    }
                }
                //更改账单状态
                $billid=unserialize($payinfo["billid"]);
                foreach ($billid as $key => $value) {
                    $billinfo=(new billService())->billIdinfo($value);
                    if($billinfo["status"]!="TRADE_SUCCESS"){
                        $billdata['status'] = 'TRADE_SUCCESS';       
                        $billdata['pay_type'] = '线下支付宝';
                        $billdata['user_id']=$payinfo["user_id"];
                        $billdata['trade_no']=$payinfo["trade_no"];
                        $billdata['gmt_payment'] =  $result['gmt_payment'];
                        $billdata['id'] = $value;
                         //修改数据
                        $billedit = (new billService())->billEdit($billdata);
                        //如果订单同步支付宝，则删除支付宝订单
                        if($billinfo["tongbu"]=="1"){
                            (new appletService())->alibilldel($billinfo['id']);
                            //Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"2"]);
                        }
                    } 
                    $detailed[]='费用类型: '.$billinfo['cost_type'];
                    $detailed[]= '账期: '.$billinfo['acct_period'];
                    $detailed[]='金额: '.$billinfo['bill_entry_amount'].'元';
                    $detailed[]='备注: '.$billinfo['remarks'];
                }

                if($payinfo["printing"]=="0"){
                    $community = (new billService())->communityMachine($payinfo['community_id']);
                    $machineCode = $community['machine_code'];//终端号
                    $community_name = $community['community_name'];//小区名称
                    $room_address = $payinfo['room_address'];//门牌号
                    $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                    $detailed = $detailed;//费用类型
                    $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                    $pay_type = "支付宝";//付款类型
                    $bill_amount =$payinfo['pay_money'];//支付金额
                    $gmt_payment =$result['gmt_payment'];//付款时间
                    $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                    $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                   
                    if($printing){
                        Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                        foreach($billid as $id){
                            $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                        }
                        
                    }
                }


            }   
                
            
        }
    }
    
    //回调信息
    public function communitycashiernotice(){
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\'.date('YmdHis').rand(100000,999999).'.txt';//文本路径
        $path=dir(getcwd())->path.'/pay/aliapplet/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\20190917163824965420.txt';
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            //如果成功返回了
            $payinfo=Db::table("billpay")->where('trade_no',$result['trade_no'])->find();
            if(!empty($payinfo)){
                if($payinfo["order_status"]=="0"){
                    $paydata["id"]=$payinfo["id"];
                    $paydata["order_status"]="1";
                    $paydata['pay_time'] =$result['gmt_payment'];
                    
                    Db::table("billpay")->update($paydata);

                    $communtyinfo=Db::table("community")->where("community_id",$payinfo["community_id"])->find();
                    if($communtyinfo["auto_invoice_send_status"]=="1"){
                        $jobHandlerClassName  = 'app\admin\job\BillInvoice';
                        $jobQueueName  	  = "BillInvoiceQueue";
                        $jobData       	  = [ 'id' => $payinfo["id"] ] ;
                        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
                    }
                }
                //更改账单状态
                $billid=unserialize($payinfo["billid"]);
                foreach ($billid as $key => $value) {
                    $billinfo=(new billService())->billIdinfo($value);
                    if($billinfo["status"]!="TRADE_SUCCESS"){
                        $billdata['status'] = 'TRADE_SUCCESS';       
                        $billdata['pay_type'] = '支付宝';
                        $billdata['user_id']=$payinfo["user_id"];
                        $billdata['trade_no']=$payinfo["trade_no"];
                        $billdata['gmt_payment'] =  $result['gmt_payment'];
                        $billdata['id'] = $value;
                        $billdata['cashier_id']=$payinfo["cashier_id"];
                         //修改数据
                        $billedit = (new billService())->billEdit($billdata);
                        //如果订单同步支付宝，则删除支付宝订单
                        if($billinfo["tongbu"]=="1"){
                            (new appletService())->alibilldel($billinfo['id']);
                            //Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"2"]);
                        }
                    } 
                    $detailed[]='费用类型: '.$billinfo['cost_type'];
                    $detailed[]= '账期: '.$billinfo['acct_period'];
                    $detailed[]='金额: '.$billinfo['bill_entry_amount'].'元';
                    $detailed[]='备注: '.$billinfo['remarks'];
                }

                if($payinfo["printing"]=="0"){
                    $community = (new billService())->communityMachine($payinfo['community_id']);
                    $cashierinfo=Db::table("community_cashier")->where("id",$payinfo["cashier_id"])->find();
                    $machineCode = $cashierinfo['machine_code'];//终端号
                    if(!empty($machineCode)){
                        $community_name = $community['community_name'];//小区名称
                        $room_address = $payinfo['room_address'];//门牌号
                        $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                        $detailed = $detailed;//费用类型
                        $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                        $pay_type = "支付宝";//付款类型
                        $bill_amount =$payinfo['pay_money'];//支付金额
                        $gmt_payment =$result['gmt_payment'];//付款时间
                        $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                        $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                       
                        if($printing){
                            Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                            foreach($billid as $id){
                                $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                            }
                            
                        }
                    }
                    
                }
            }   
                
            
        }
    }
    //回调信息
    public function wxnotice(){
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\'.date('YmdHis').rand(100000,999999).'.txt';//文本路径
        $path=dir(getcwd())->path.'/pay/wxnotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\20190917163824965420.txt';
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            //如果成功返回了
            $payinfo=Db::table("billpay")->where('trade_no',$result['out_trade_no'])->find();
            if(!empty($payinfo)){
                if($payinfo["order_status"]=="0"){
                    $paydata["id"]=$payinfo["id"];
                    $paydata["order_status"]="1";
                    $paydata['pay_time'] =$result['time_end'];
                    
                    Db::table("billpay")->update($paydata);
                }
                //更改账单状态
                $billid=unserialize($payinfo["billid"]);
                foreach ($billid as $key => $value) {
                    $billinfo=(new billService())->billIdinfo($value);
                    if($billinfo["status"]!="TRADE_SUCCESS"){
                        $billdata['status'] = 'TRADE_SUCCESS';       
                        $billdata['pay_type'] = '微信';
                        $billdata['user_id']=$payinfo["user_id"];
                        $billdata['trade_no']=$payinfo["trade_no"];
                        $billdata['gmt_payment'] =  $result['time_end'];
                        $billdata['id'] = $value;
                         //修改数据
                        $billedit = (new billService())->billEdit($billdata);
                        //如果订单同步支付宝，则删除支付宝订单
                        if($billinfo["tongbu"]=="1"){
                            (new appletService())->alibilldel($billinfo['id']);
                            Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"1"]);
                        }
                    } 
                    $detailed[]='费用类型: '.$billinfo['cost_type'];
                    $detailed[]= '账期: '.$billinfo['acct_period'];
                    $detailed[]='金额: '.$billinfo['bill_entry_amount'].'元';
                    $detailed[]='备注: '.$billinfo['remarks'];
                }

                if($payinfo["printing"]=="0"){
                    $community = (new billService())->communityMachine($payinfo['community_id']);
                    $machineCode = $community['machine_code'];//终端号
                    $community_name = $community['community_name'];//小区名称
                    $room_address = $payinfo['room_address'];//门牌号
                    $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                    $detailed = $detailed;//费用类型
                    $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                    $pay_type = "微信";//付款类型
                    $bill_amount =$payinfo['pay_money'];//支付金额
                    $gmt_payment =$result['time_end'];//付款时间
                    $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                    $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                   
                    if($printing){
                        Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                        foreach($billid as $id){
                            $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                        }
                        
                    }
                }
            }   
                
            
        }
    }
    
    //回调信息
    public function alinotice_discount(){
        $path=dir(getcwd())->path.'\pay\aliapplet\\'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."\\".date('His').rand(100000,999999).'.txt';
        //die;
        //$address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\20191204\150254655880.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            //如果成功返回了
            $payinfo=Db::table("billpay")->where('trade_no',$result['trade_no'])->find();
            if(!empty($payinfo)){
                if($payinfo["order_status"]=="0"){
                    $paydata["id"]=$payinfo["id"];
                    $paydata["order_status"]="1";
                    $paydata['pay_time'] =$result['gmt_payment'];
                    
                    Db::table("billpay")->update($paydata);
                }
                //更改账单状态
                $billid=unserialize($payinfo["billid"]);
                $discount_id=json_decode($payinfo["discount_billid"],true);
                foreach ($billid as $key => $value) {
                    $billinfo=(new billService())->billIdinfo($value);
                    if($billinfo["status"]!="TRADE_SUCCESS"){
                        $billdata['status'] = 'TRADE_SUCCESS';       
                        $billdata['pay_type'] = '支付宝';
                        $billdata['user_id']=$payinfo["user_id"];
                        $billdata['trade_no']=$payinfo["trade_no"];
                        $billdata['gmt_payment'] =  $result['gmt_payment'];
                        $billdata['id'] = $value;
                        if($discount_id[$value]["discount_status"]=="1")
                        {
                            $billdata['discount_money']=$discount_id[$value]["money"]."(".$discount_id[$value]["discount_rate"].")";
                        }else
                        {
                            $billdata['discount_money']="";
                         
                        }
                        //修改数据
                        $billedit = (new billService())->billEdit($billdata);
                        //如果订单同步支付宝，则删除支付宝订单
                        if($billinfo["tongbu"]=="1"){
                            (new appletService())->alibilldel($billinfo['id']);
                            Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"3"]);
                        }
                    } 

                    $detailed[]='费用类型: '.$billinfo['cost_type'];
                    $detailed[]= '账期: '.$billinfo['acct_period'];
                    $str='金额: '.$billinfo['bill_entry_amount'].'元';
                    if($discount_id[$value]["discount_status"]=="1")
                    {
                        //$str='金额: '.$discount_id[$value]["money"].'元(折扣)';
                        $str='金额: '.$discount_id[$value]["money"].'元';
                    }
                    $detailed[]=$str;
                }

                if($payinfo["printing"]=="0"){
                    $community = (new billService())->communityMachine($payinfo['community_id']);
                    $machineCode = $community['machine_code'];//终端号
                    $community_name = $community['community_name'];//小区名称
                    $room_address = $payinfo['room_address'];//门牌号
                    $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                    $detailed = $detailed;//费用类型
                    $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                    $pay_type = "支付宝";//付款类型
                    $bill_amount =$payinfo['pay_money'];//支付金额
                    $gmt_payment =$result['gmt_payment'];//付款时间
                    $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                    $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                   
                    if($printing){
                        Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                        foreach($billid as $id){
                            $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                        }
                        
                    }
                }
            }   
                
            
        }
    }
    public function testalinotice(){
        
        
        $address = 'C:\phpStudy\WWW\zaozao\public\pay\aliapplet\\20191007151428618060.txt';
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            //如果成功返回了
            $payinfo=Db::table("billpay")->where('trade_no',$result['trade_no'])->find();
            if(!empty($payinfo)){
                if($payinfo["order_status"]=="0"){
                    $paydata["id"]=$payinfo["id"];
                    $paydata["order_status"]="1";
                    $paydata['pay_time'] =$result['gmt_payment'];
                    
                    Db::table("billpay")->update($paydata);
                }
                //更改账单状态
                $billid=unserialize($payinfo["billid"]);
                foreach ($billid as $key => $value) {
                    $billinfo=(new billService())->billIdinfo($value);
                    if($billinfo["status"]!="TRADE_SUCCESS"){
                        $billdata['status'] = 'TRADE_SUCCESS';       
                        $billdata['pay_type'] = '支付宝';
                        $billdata['user_id']=$payinfo["user_id"];
                        $billdata['gmt_payment'] =  $result['gmt_payment'];
                        $billdata['id'] = $value;
                         //修改数据
                        $billedit = (new billService())->billEdit($billdata);
                        //如果订单同步支付宝，则删除支付宝订单
                        if($billinfo["tongbu"]=="1"){
                            (new appletService())->alibilldel($billinfo['id']);
                            Db::table("bill")->where('id',$billinfo['id'])->update(["tongbu"=>"3"]);
                        }
                    } 
                    $detailed[]='费用类型: '.$billinfo['cost_type'];
                    $detailed[]= '账期: '.$billinfo['acct_period'];
                    $detailed[]='金额: '.$billinfo['bill_entry_amount'].'元';
                }

                if($payinfo["printing"]=="0"){
                    $community = (new billService())->communityMachine($payinfo['community_id']);
                    $machineCode = $community['machine_code'];//终端号
                    $community_name = $community['community_name'];//小区名称
                    $room_address = $payinfo['room_address'];//门牌号
                    $owner_name = (new billService())->billOwnerName($payinfo['out_room_id']);//业主姓名
                    $detailed = $detailed;//费用类型
                    $trade_no =$payinfo['out_trade_no'];//支付宝订单号
                    $pay_type = "支付宝";//付款类型
                    $bill_amount =$payinfo['pay_money'];//支付金额
                    $gmt_payment =$result['gmt_payment'];//付款时间
                    $property = (new billService())->propertyIdName($community['property_id']);//收款单位
                    $printing = (new printDemo())->payprinting($machineCode,$community_name,$room_address,$owner_name,$detailed,$trade_no,$pay_type,$bill_amount,$gmt_payment,$property);
                   
                    if($printing){
                        Db::table('billpay')->where('id', $payinfo["id"])->update(['printing' => '1']);
                        foreach($billid as $id){
                            $dayin = Db::name('bill')->where('id', $id)->update(['printing' => '1']);
                        }
                        
                    }
                }
            }   
                
            
        }
    }
}